package com.web.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.web.bdo.User;
import com.web.bdo.dao.UserDao;
import com.web.forms.SignupForm;
import com.web.forms.UserForm;

public class UpdateUserAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		ActionErrors errors = new ActionErrors();
		
		if (isCancelled(request)) {
			errors.add("cancelEdit", new ActionMessage("cancel.editUser"));
			saveMessages(request, errors);			
			return mapping.findForward("error");
		}
		
		UserForm userForm = (UserForm)form;
		errors = userForm.validate(mapping, request);
		
		if (!errors.isEmpty()) {
			errors.add("heading", new ActionMessage("errors.editUser.heading"));
			saveMessages(request, errors);			
			return mapping.findForward("error");
		}
		
		User user = new User(); 
		BeanUtils.copyProperties(user, userForm);
		UserDao userDao = new UserDao();
		errors = userDao.update(user);
		
		if (!errors.isEmpty()) {
			errors.add("heading", new ActionMessage("errors.editUser.heading"));
			saveMessages(request, errors);			
			return mapping.findForward("error");
		}
		
		return mapping.findForward("success");
	}
	
}
